package cn.lili.modules.order.order.callback;

import cn.hutool.core.collection.CollectionUtil;
import cn.lili.cache.Cache;
import cn.lili.cache.CachePrefix;
import cn.lili.common.event.TransactionCommitSendMQEvent;
import cn.lili.common.vo.ResponseBean;
import cn.lili.common.vo.ResultMessage;
import cn.lili.exchange.AmqpExchangeProperties;
import cn.lili.modules.goods.client.GoodsClient;
import cn.lili.modules.goods.client.GoodsSkuClient;
import cn.lili.modules.goods.entity.dos.Goods;
import cn.lili.modules.goods.entity.dos.GoodsSku;
import cn.lili.modules.goods.entity.enums.GoodsAuthEnum;
import cn.lili.modules.goods.entity.enums.GoodsMarketEnum;
import cn.lili.modules.goods.entity.vos.yunxin.CallBackVO;
import cn.lili.modules.order.order.service.MessageTypeFlowService;
import cn.lili.routing.GoodsRoutingKey;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.transaction.annotation.ShardingTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品删除
 */
@Slf4j
@Service("goods.delete")
public class GoodsDeleteService implements MessageType{

    @Autowired
    private GoodsClient goodsClient;
    @Autowired
    private GoodsSkuClient goodsSkuClient;
    @Autowired
    private MessageTypeFlowService messageTypeFlowService;
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;
    @Autowired
    private AmqpExchangeProperties amqpExchangeProperties;
    @Autowired
    private Cache cache;

    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public ResponseBean execute(CallBackVO callBackVO) {
        log.info("goods.undercarriage == {}", JSONObject.toJSONString(callBackVO));
        //保存回调消息记录
        messageTypeFlowService.saveCall(callBackVO);

        //根据第三方平台id，获取商品信息。
        List<Goods> goodsList = goodsClient.getByThirdPartyPlatformId(callBackVO.getProduct_id());
        log.info("根据第三方平台id，获取商品信息 == {} ", JSONObject.toJSONString(goodsList));
        List<String> skuIdList = new ArrayList<>();
        List<GoodsSku> skuList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(goodsList)) {
            skuList = goodsSkuClient.getGoodsSkuByGoodsIdList(goodsList.stream().map(Goods::getId).collect(Collectors.toList()));
            if (CollectionUtil.isNotEmpty(skuList)) {
                skuIdList = skuList.stream().map(GoodsSku::getId).map(String::valueOf).collect(Collectors.toList());
            }
        }

        //删除商品
        if (CollectionUtil.isNotEmpty(goodsList)) {
            List<String> goodsIds = goodsList.stream().map(Goods::getId).map(String::valueOf).collect(Collectors.toList());
            goodsClient.deleteGoods(goodsIds);
        }
        log.info("删除商品sku skuList == {}", JSONObject.toJSONString(skuList));
        if (CollectionUtil.isNotEmpty(skuList)) {
            for (GoodsSku goodsSku : skuList) {
                goodsSku.setDeleteFlag(true);
            }
            goodsSkuClient.updateBatchById(skuList);
        }

        //删除缓存 + 索引
        List<String> goodsCacheKeys = new ArrayList<>();
        for (Goods gs : goodsList) {
            goodsCacheKeys.add(CachePrefix.GOODS.getPrefix() + gs.getId());
            applicationEventPublisher.publishEvent(TransactionCommitSendMQEvent.builder().source("删除商品").exchange(amqpExchangeProperties.getGoods()).routingKey(GoodsRoutingKey.GOODS_DELETE).message(gs.getId()).build());
        }
        skuIdList.forEach(skuId -> cache.remove(CachePrefix.GOODS_SKU.getPrefix() + skuId));
        cache.multiDel(goodsCacheKeys);

        return new ResponseBean(0, "操作成功", new HashMap<>());
    }
}
